//*************************************************************************//
//*           _____   ____________            ______               __     *//
//*          / /__ \ / ____/ ____/           / ____/___  _________/ /     *//
//*     __  / /__/ // __/ / __/    ______   / /_  / __ \/ ___/ __  /      *//
//*    / /_/ // __// /___/ /___   /_____/  / __/ / /_/ / /  / /_/ /       *//
//*    \____//____/_____/_____/           /_/    \____/_/   \__,_/        *//
//*                                                                       *//
//*     Copyright (c) 2006 Ford Argentina. All Rights Reserved.           *//
//*                                                                       *//
//*************************************************************************//

package ar.com.ford.it.webengine.listener;

import oracle.toplink.sessions.Session;
import oracle.toplink.tools.sessionmanagement.SessionManager;
import ar.com.ford.it.webengine.logger.Log4jToplinkLog;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceHelper;
import com.ford.it.properties.PropertyGroup;
import com.ford.it.properties.PropertyManager;

public class PersistenceInitializer {
    private static final String CLASS_NAME = PersistenceInitializer.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(CLASS_NAME);

    public static final String PERSISTENCE_CONFIG = "/resources/persistence-config.xml";

	
	/**
	 * Inicializar framework de persistencia.
	 * @throws Exception
	 */
    public void initPersistenceFramework() throws Exception {
        String METHOD_NAME="initPersistenceFramework";
        log.entering(CLASS_NAME, METHOD_NAME);

        PersistenceHelper.initialize(PERSISTENCE_CONFIG);

        PropertyManager pMgr = PropertyManager.getInstance();

        pMgr.load(getClass().getResourceAsStream(PERSISTENCE_CONFIG));
        PropertyGroup root = pMgr.getChildGroup("PersistenceConfig");

		if (root!=null) {
	        PropertyGroup pg = (PropertyGroup) root.getChildGroups().next();
	
	       	String sessionName = pg.getString("toplinkSessionName");
	       	if (sessionName==null) {
	       		// Valor por defecto
	       		sessionName = pg.getName();
	       	}
	       	
	       	log.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "sessionName", sessionName);
	        
	        Session session = SessionManager.getManager().getSession(sessionName);
			
			// Inicializar el logger de toplink
			session.setSessionLog(new Log4jToplinkLog());
			session.logMessages();

	       	log.logp(Level.FINE, CLASS_NAME, METHOD_NAME, "Session inicializada");
		}
        
        log.exiting(CLASS_NAME, METHOD_NAME);
    }
    
}
